function intersect(nums1, nums2) {
    nums1.sort((a, b) => a - b)
    nums2.sort((a, b) => a - b)
    let i = 0
    let j = 0
    const result = []
    while(i < nums1.length && j < nums2.length) {
        const num1 = nums1[i]
        const num2 = nums2[j]
        if (num1 === num2) {
            result.push(num1)
            i++
            j++
        } else if (num1 > num2) {
            j++
        } else if (num1 < num2) {
            i++
        }
    }
    return result
}

const nums1 = [4,9,5]
const nums2 = [9,4,9,8,4]
console.log(intersect(nums1, nums2))


function intersect1(nums1, nums2) {
    const map = new Map()
    const list = []
    for (let index = 0; index < nums1.length; index++) {
        let value = map.get(nums1[index])
        if (value === undefined) {
            map.set(nums1[index], 1)
        } else {
            map.set(nums1[index], ++value)
        }
    }
    for (let index = 0; index < nums2.length; index++) {
        let value = map.get(nums2[index])
        if (value && value > 0) {
            list.push(nums2[index])
            map.set(nums2[index], --value)
        }
    }
    return list
}

console.log(intersect1(nums1, nums2))